package kr.hkit.androidcomplete03.ch25;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import kr.hkit.androidcomplete03.R;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class FileIO extends Activity {
	EditText edit;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch25_fileio);
		
		edit = (EditText) findViewById(R.id.ch25_fileio_edittext);
	}
	
	public void mOnClick(View v ){
		switch (v.getId()) {
		case R.id.ch25_fileio_save:
			FileOutputStream fos;
			try {
				fos = openFileOutput("test.txt", Context.MODE_WORLD_READABLE);
				String str = "Android File IO Test 어딨냐 이거";
				fos.write(str.getBytes());
				edit.setText("Write Success");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			break;

		case R.id.ch25_fileio_load:
			FileInputStream fis;
			try {
				fis = openFileInput("test.txt");
				byte[] data = new byte[fis.available()];
				
				while(fis.read(data) != -1){
				}
				
				fis.close();
				edit.setText(new String(data));
			} catch (FileNotFoundException e) {
				edit.setText("File Not Found");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			break;
			
		case R.id.ch25_fileio_loadres:
			try {
				InputStream fres = getResources().openRawResource(R.raw.restext);
				byte[] data = new byte[fres.available()];
				
				while(fres.read(data) != -1){}
				fres.close();
				edit.setText(new String(data));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
			
		case R.id.ch25_fileio_delete:
			if(deleteFile("test.txt")){
				edit.setText("delete success");
			}else{
				edit.setText("delete failed");
			}
			break;
		}
	}
}
